package com.snow.useviewdemo.function2.darkmode;

import android.content.Context;
import android.content.res.Configuration;
import android.os.Build;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatDelegate;

import com.snow.useviewdemo.R;
import com.snow.useviewdemo.base.BaseActivity;
import com.snow.useviewdemo.databinding.ActivityDarkModeTestBinding;

/**
 * Created by zhaoyingtao
 * Date: 2020/9/24
 * Describe:研究深色模式
 */
public class DarkModeTestActivity extends BaseActivity<ActivityDarkModeTestBinding> {
    @Override
    protected int getLayoutId() {
        return R.layout.activity_dark_mode_test;
    }

    @Override
    protected void setViewData(Bundle savedInstanceState) {
        mBinding.textview01.setText("当前深色模式是否打开==" + isNightMode(this));
        mBinding.button01.setOnClickListener(view -> {
            setDarkState();
            darkState = !darkState;
        });
    }

    @Override
    public void onConfigurationChanged(@NonNull Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        int currentNightMode = newConfig.uiMode & Configuration.UI_MODE_NIGHT_MASK;
        switch (currentNightMode) {
            case Configuration.UI_MODE_NIGHT_NO:
                mBinding.textview01.setText("当前深色模式关闭==" + isNightMode(this));
                // 关闭
                break;
            case Configuration.UI_MODE_NIGHT_YES:
                mBinding.textview01.setText("当前深色模式开启==" + isNightMode(this));
                // 开启
                break;
            default:
                break;
        }
    }

    private boolean darkState;

    /**
     * 只有用户打开了深色模式，切换才有效，但只针对当前应用，退出后又会跟随系统
     * 用户没有打开深色模式，此方法并不能切换，切换无效
     * 浅色 - MODE_NIGHT_NO
     * 深色 - MODE_NIGHT_YES
     * 由省电模式设置 - MODE_NIGHT_AUTO_BATTERY
     * 系统默认 - MODE_NIGHT_FOLLOW_SYSTEM
     */
    private void setDarkState() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            if (darkState) {
                AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
            } else {
                AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
            }
        } else {
            AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_AUTO_BATTERY);
        }
    }

    /**
     * 判断是不是深色模式
     *
     * @param context
     * @return
     */
    public static boolean isNightMode(Context context) {
        int currentNightMode = context.getResources().getConfiguration().uiMode &
                Configuration.UI_MODE_NIGHT_MASK;
        return currentNightMode == Configuration.UI_MODE_NIGHT_YES;
    }


}
